package game

import (
	"fmt"
	"math"
	"server/db"
	"strconv"
	"strings"
	"time"
)

type OldPlayerCompensateMgr struct {
	MSqlCompensateStruct map[string]*db.SqlCompensateStruct
}

func (p *OldPlayerCompensateMgr) SuccessSendEmail(username string) bool {

	emailst, ok := p.MSqlCompensateStruct[username]
	if ok {
		emailst.IsSendEmail = 1
		db.FormatAllMemUpdateDb(emailst, "t_player_compensate_Data", "auto_id")
		return true
	}
	return false
}

func (p *OldPlayerCompensateMgr) SendEmailToDb(username string, dwUin int32) bool {

	emailst, ok := p.MSqlCompensateStruct[username]
	if ok {
		if emailst.IsSendEmail == 1 {
			return false
		} else {
			sqlSt := &db.SqlEmailStruct{}
			sqlSt.DwUin = dwUin
			sqlSt.Content = `Welcome back to our game!
Here comes your refund for your scene progress and payment in test version!
Have fun in new version!`
			sqlSt.CurrencyCount = 0
			sqlSt.CurrencyInfo = ""
			sqlSt.RecvTime = 0
			sqlSt.Title = "Test Players' Refund"
			sqlSt.Sender = "System"
			sqlSt.ItemCount = 0
			sqlSt.ItemInfo = ""
			sqlSt.SendTime = int32(time.Now().Unix())
			sqlSt.Status = 0
			sqlSt.Type = 1
			sqlSt.RewardId = ""
			sqlSt.RewardCount = ""
			sqlSt.LinkUrl = ""
			strarr := []string{}
			if emailst.DecorationCnt-5 > 0 {
				SceneDiamond := (emailst.DecorationCnt-5)*10 + 25

				temp := fmt.Sprintf("Diamond|%d", SceneDiamond)
				strarr = append(strarr, temp)
			}
			f, err := strconv.ParseFloat(emailst.ChargeCnt, 64)
			var ChargeDiamond float64 = 0
			if err == nil {
				ChargeDiamond = f * 1.5 * 75
			}
			if ChargeDiamond > 0 {
				cd := int32(math.Ceil(ChargeDiamond))
				remain := cd % 10
				if remain != 0 && remain != 5 {
					if remain < 5 {
						cd = cd - remain + 5
					} else {
						cd = cd - remain + 10
					}
				}
				temp := fmt.Sprintf("Diamond|%d", cd)
				strarr = append(strarr, temp)

			}
			sqlSt.RewardType = strings.Join(strarr, "_")

			insertId, err1 := db.FormatAllMemInsertDb(sqlSt, "system_mail_info")

			if err1 == nil {
				p.SuccessSendEmail(username)
				fmt.Sprintln("Success Intert Mail:" + strconv.Itoa(int(insertId)))
			}

			return true
		}

	}
	return false
}

func (p *OldPlayerCompensateMgr) LoadData() {
	sqlStr := "SELECT * FROM t_player_compensate_Data"
	sqlStrucks := []db.SqlCompensateStruct{}

	p.MSqlCompensateStruct = make(map[string]*db.SqlCompensateStruct)
	if err := db.SqlDb.Select(&sqlStrucks, sqlStr); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		return
	} else {

	}
	for i := 0; i < len(sqlStrucks); i++ {
		p.MSqlCompensateStruct[sqlStrucks[i].DeviceId] = &sqlStrucks[i]
	}

}

func (p *OldPlayerCompensateMgr) InitManager() {
	p.LoadData()
}
